#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<string>
using namespace std;

//有1000张票待抢
int ticket = 1000;
//静态方式
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* routine(void* msg)
{
    string _msg = static_cast<char*>(msg);
    while(true)  //剩余票数大于0就一直抢票
    {
        //
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        if(ticket>0)
        {
        cout<<_msg<<"---->"<<ticket<<endl; 
        ticket--;
            pthread_mutex_unlock(&mutex);      
        }
        else
        {
            pthread_mutex_unlock(&mutex);      
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t tid[4];  //创建四个新线程一起抢票
    //创建新线程
    for(int i=0;i<4;++i)
    {
        char* buff = new char[32];
        snprintf(buff,sizeof(buff),"thread%d",i);
        pthread_create(tid+i,nullptr,routine, buff);
    }

    //测试用，主线程隔一秒唤醒一次。
    while(true)
    {
        sleep(1);  
        pthread_mutex_lock(&mutex);
        pthread_cond_broadcast(&cond);
        cout<<"main thread is wake up"<<endl;
        pthread_mutex_unlock(&mutex);      
    }

    //线程等待
    for(int i=0;i<4;++i)
    {
        pthread_join(tid[i],nullptr);
    }

    return 0;
}